# Contingency table

## Data
library(vcd)
str(Arthritis)
head(Arthritis)

## Create 1d frequency table
t1d <- table(Arthritis$Improved)
t1d

prop.table(t1d)
prop.table(t1d) * 100

## Create 2d frequency table

t2d1 <- with(Arthritis, table(Treatment, Improved))

t2d2 <- xtabs(~ Treatment + Improved, data = Arthritis)

margin.table(t2d1, 1)

prop.table(t2d2, 1)

margin.table(t2d1, 2)

prop.table(t2d2, 2)

prop.table(t2d1)

addmargins(t2d1)
addmargins(prop.table(t2d2))

addmargins(t2d1, 1)
addmargins(prop.table(t2d1, 2), 1)

addmargins(t2d1, 2)
addmargins(prop.table(t2d1, 1), 2)

## Multi-dimensions table

t3d <- xtabs( ~ Treatment + Sex + Improved, data = Arthritis)
t3d
ftable(t3d)

margin.table(t3d, 1)

margin.table(t3d, 2)

margin.table(t3d, 3)

margin.table(t3d, c(1, 3))

ftable(margin.table(t3d, c(1, 2)))

ftable(addmargins(prop.table(t3d, c(1, 2)), 3))
